package edu.wtbu.cs.androiddemo.net;


import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;

public class JsonUtil {
    public static  JsonUtil instance;
    private static Gson gson;
    public static JsonUtil getInstance(){
        if(instance == null){
            synchronized (JsonUtil.class){
                if(instance == null){
                    instance = new JsonUtil();
                    synchronized (Gson.class){
                        gson = new Gson();
                    }
                }
            }
        }
        return instance;
    }
    public<T> String beanToJsonStr(T t){
        String str="";
        if(t != null){
            str = gson.toJson(t);
        }
        return str;
    }
    // 把字符变为对象实体
    public<T>  T jsonToBean(String jsonStr, Class<T> tClass){
        T t =null;
        if(jsonStr !=null || jsonStr != ""){
            try {
                t = gson.fromJson(jsonStr,tClass);
            }catch (JsonIOException e){
            }
        }
        return t;
    }
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

        ArrayList<T> list = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            list.add(new Gson().fromJson(jsonObject, clazz));
        }
        return list;
    }
}
